/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package br.com.jr2tecnologia;


import br.com.jr2tecnologia.mail.Mailbox;
import br.com.jr2tecnologia.model.KeyResponsePersistenceLocal;
import br.com.jr2tecnologia.model.LoginPersistenceLocal;
import br.com.jr2tecnologia.model.ModemPersistenceLocal;
import br.com.jr2tecnologia.model.RolePersistenceLocal;
import br.com.jr2tecnologia.model.SmsReceivedPersistenceLocal;
import br.com.jr2tecnologia.model.SmsSendPersistenceLocal;
import br.com.jr2tecnologia.model.entity.Company;
import br.com.jr2tecnologia.model.entity.KeyResponse;
import br.com.jr2tecnologia.model.entity.Login;
import br.com.jr2tecnologia.model.entity.Modem;
import br.com.jr2tecnologia.model.entity.SmsReceived;
import br.com.jr2tecnologia.model.entity.SmsSend;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.logging.Logger;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author ronildo
 */
public class HTTPConnectorNowSMS extends HttpServlet {

    private static final Logger logger = LoggerFactory.getLogger();

    @EJB
    private SmsReceivedPersistenceLocal smsReceivedPersistence;
    @EJB
    private KeyResponsePersistenceLocal keyResponsePersistence;
    @EJB
    private ModemPersistenceLocal modemPersistence;
    @EJB
    private SmsSendPersistenceLocal smsSendPersistence;
    @EJB
    private RolePersistenceLocal rolePersistence;
    @EJB
    private LoginPersistenceLocal loginPersistence;

    private void write(HttpServletResponse response, String txt){
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = null;
        try {
            out = response.getWriter();
            out.println(txt);
        } catch (IOException ex) {
            logger.info("error to write in page of response");
        } finally{
            if(out != null)
                out.close();
        }
    }
   
    protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String sender = request.getParameter("sender");
        String fullsms = request.getParameter("fullsms");
        String messageid = request.getParameter("messageid");
        String receiptmessageid = request.getParameter("receiptmessageid");
        String smsroute = request.getParameter("smsroute");
        String msgdate = request.getParameter("msgdate");
        String msgtime = request.getParameter("msgtime");

        if(sender == null || sender.equals("") || fullsms == null || fullsms.equals("")){
            write(response, "Missing paramaters");
            logger.info("Missing paramaters");
        }else if( modemPersistence.findModemBySmscRoute(smsroute) == null){
            write(response, "Modem not found: " + smsroute);
            logger.info("Modem not found: " + smsroute);
        }else if(!receiptmessageid.equals("")){
            logger.info("recebendo confirmação de entrega de sms");
            SmsSend smsSend = smsSendPersistence.findByNowSmsId(receiptmessageid);
            if(smsSend != null){
                smsSend.setDelivered(true);
                smsSendPersistence.update(smsSend);
            }
        }else{
            logger.info("receiving request from '" + request.getLocalAddr() + 
                    "' sender:'"+sender+"' with message:'"+fullsms+"' messageid:'"+
                    messageid+"' receiptmessageid:'"+receiptmessageid+"' smsroute:'"+
                    smsroute+"' msgdate:'"+msgdate+"' msgtime:'"+msgtime+"'");

            if(sender.substring(0,1).equals("+")){
                sender = sender.substring(1);
            }

            SmsReceived smsReceived = processesReceiving(sender, fullsms, smsroute, messageid, msgdate+msgtime);
            smsReceivedPersistence.persist(smsReceived);
            write(response, "SMS '"+sender+"' Received and put in database");
        }
    }

    private SmsReceived processesReceiving(String sender, String txt, String smsroute, String receiptmessageid, String dateTime){
        Modem modem = modemPersistence.findModemBySmscRoute(smsroute);
        SmsReceived smsReceived = new SmsReceived();
        smsReceived.setMessage(txt);
        smsReceived.setSender(sender);
        smsReceived.setDatetimeReceived(new Date());
        smsReceived.setNowSmsId(receiptmessageid);
        smsReceived.setDatetimeReceivedInModem(SMSUtil.parseDate(dateTime,SMSUtil.DATE_NOWSMS));
        smsReceived.setModem(modem);

        Login loginOfModem = modem.getLogin();
        Company companyOfModem = modem.getCompany();
        KeyResponse keyResponse = findKeyResponseInSMSText(txt);
        Login loginWhoSentLast = smsSendPersistence.findWhoSentLast(sender);

        
        if(loginOfModem != null){
            logger.info("this modem '"+modem.getName()+"' belongs to login: " + loginOfModem.getEmail());
            smsReceived.setLogin(loginOfModem);
            Mailbox.post(loginOfModem.getEmail(), sender, smsReceived.getMessage());
        }else if(companyOfModem != null){
            logger.info("this modem '"+modem.getName()+"' belongs to company: " + loginOfModem.getCompany().getName());
            Login loginSearch = new Login();
            loginSearch.setCompany(companyOfModem);
            loginSearch.setRole(rolePersistence.findByName("Administrator"));
            Login loginChosed = loginPersistence.list(loginSearch).get(0);
            smsReceived.setLogin(loginChosed);
            Mailbox.post(loginChosed.getEmail(), sender, smsReceived.getMessage());
        }else if (keyResponse != null){
            smsReceived.setKeyResponse(keyResponse);
            Login loginOfKeyResponse = keyResponse.getLogin();
            logger.info("this response key: '"+keyResponse.getName()+"'. Belongs to login: " + loginOfKeyResponse.getName());
            smsReceived.setLogin(loginOfKeyResponse);
            Mailbox.post(loginOfKeyResponse.getEmail(), sender, smsReceived.getMessage());
        }else if (loginWhoSentLast != null){
            logger.info("this is who sent last sms: '" + loginWhoSentLast.getEmail());
            smsReceived.setLogin(loginWhoSentLast);
            Mailbox.post(loginWhoSentLast.getEmail(), sender, smsReceived.getMessage());
        }else{
            smsReceived.setLogin(loginPersistence.findLoginByEmail("ronildo@jr2tecnologia.com.br"));
            Mailbox.post("ronildo@jr2tecnologia.com.br", sender, smsReceived.getMessage());
        }
        

        return smsReceived;
    }

    private KeyResponse findKeyResponseInSMSText(String txt){
        if(txt.indexOf(" ") == -1)
            return null;

        String key = txt.substring(0, txt.indexOf(" "));
        KeyResponse keyResponse = keyResponsePersistence.findByNameWithoutCasesensitive(key);
        if(keyResponse != null)
            return keyResponse;
        else
            return null;
    }
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    } 

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

    @Override
    public String getServletInfo() {
        return "Servlet InboundNowSMS";
    }
}
